package com.example.zhang;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.app.ListActivity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.GridView;
import android.widget.ListAdapter;
import android.widget.ListView;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.util.ArrayList;

public class MylistActivity_button extends AppCompatActivity implements Runnable {
    private static final String TAG ="a" ;
    ListView listView;
    String name;
    float data;
    Handler handler;
    ArrayList<String> sites_test = new ArrayList<String>();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_mylist_button);
        GridView listView = findViewById(R.id.list);
        Thread t = new Thread((Runnable) this);//开启后会启动子线程中的run方法.
        t.start();

        handler = new Handler(){
            @SuppressLint("HandlerLeak")
            @Override
            public void handleMessage(@NonNull Message msg){
                if(msg.what==1){
                    ArrayList<String> sites = (ArrayList<String>)msg.obj;
                    ListAdapter adapter = new ArrayAdapter<String>(MylistActivity_button.this, android.R.layout.simple_list_item_1,sites);
                    listView.setAdapter(adapter);
                    listView.setEmptyView(findViewById(R.id.nodata));
                }
                super.handleMessage(msg);
            }
        };

    }

    public void setHandler(Handler h){
        this.handler = h;
    }
    public void setData(String name,float data){this.name = name;this.data = data;}
    public void run(){
        try {
            Document doc = Jsoup.connect("https://www.boc.cn/sourcedb/whpj/").get();
            Element pro = doc.getElementsByTag("table").get(1);
            Elements pros = pro.getElementsByTag("tr");

            for (Element ppro : pros) {
                Elements data1 = ppro.getElementsByTag("td");
                if (data1.size() > 0 && !data1.get(1).text().isEmpty()) {
                    name = data1.get(0).text();
                    data = Float.parseFloat(data1.get(1).text());
                    sites_test.add(name+"---"+data);
                    Log.i(TAG, name+"......."+data);
                }
            }
        }

        catch(IOException e){
            e.printStackTrace();
        }
        Message msg1 = handler.obtainMessage(1);
        msg1.obj =sites_test;
        handler.sendMessage(msg1);

    }
}